<!-- 资源汇总 -->
<template>
  <ContainerLayout class="resource-management">
    <div class="form-container">
      <el-form ref="formRef" :inline="true" :model="queryForm" class="query-form" label-width="40px">
        <el-form-item label="用户">
          <el-input v-model="queryForm.user" clearable placeholder="请输入" style="width: 100px" />
        </el-form-item>
        <el-form-item label="部门">
          <el-cascader :options="deptList" :props="deptProps" style="width: 290px" v-model="queryForm.deptIds" collapse-tags clearable />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="queryForm.timelogCategory" placeholder="选择" style="width: 80px">
            <el-option label="全部" value="" />
            <el-option v-for="item in projectTypes" :key="item.dictCode" :label="`${item.dictLabel}`" :value="item.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="项目" v-if="queryForm.timelogCategory === '0'">
          <el-select v-model="queryForm.projectId" placeholder="请选择项目" style="width: 160px">
            <el-option v-for="item in projectList" :key="item.code" :label="`${item.code}-${item.cname}`" :value="item.id" />
          </el-select>
        </el-form-item>
        <TimeSlotDatePicker label="时段" v-model="queryForm.date" />
        <el-form-item>
          <el-button type="primary" @click="handleClickBtnSubmit" :icon="Search">查询</el-button>
          <el-button @click="handleClickBtnReset" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-container">
      <template v-if="isQueryed">
        <template v-if="tableData.length">
          <div class="table-title">{{ projectTitle }}</div>
          <div class="table-wrap" ref="tableWrap">
            <el-table ref="dataTable" :data="tableData" style="width: 100%" border scrollbar-always-on :summary-method="getSummaries" show-summary :height="tableHeight" header-cell-class-name="table-header-row" empty-text="没有数据">
              <el-table-column prop="parentDeptName" label="地区" width="150" fixed />
              <el-table-column prop="deptName" label="部门" width="120" fixed />
              <template v-for="item in tableColumnDate">
                <el-table-column :prop="item.label" width="70" resizable>
                  <template #header>
                    <div class="table-header-cell">
                      <div>{{ item.label }}</div>
                      <!-- <div>{{ item.end }}</div> -->
                    </div>
                  </template>
                  <template #default="scope">
                    {{ scope.row[item.columnName + ':val'] }}
                  </template>
                </el-table-column>
              </template>
            </el-table>
          </div>
        </template>
        <template v-else>
          <div class="table-title" v-if="projectTitle !== ''">{{ projectTitle }}</div>
          <el-empty description="没有查询到符合条件的数据" />
        </template>
      </template>
      <template v-else>
        <el-empty description="尚未查询数据" />
      </template>
    </div>
  </ContainerLayout>
</template>
<script lang="ts" setup>
import ContainerLayout from '../layout/ContainerLayout.vue'
import { onMounted, reactive, ref, nextTick, h } from 'vue'
import IProjectTypes from '../interface/IProjectTypes'
import { useDeptStore, useProjectssStore, useTaskTypeStore } from '../stores'
import http from '../http'
import { Refresh, Search } from '@element-plus/icons-vue'
import * as utils from '../utils'
import { ElMessage } from 'element-plus'
import TimeSlotDatePicker from '../layout/FormTableLayout/TimeSlotDatePicker.vue'

const isQueryed = ref(false)
const deptStore = useDeptStore()
const deptList = ref(deptStore.getAllState())
const projectssStore = useProjectssStore()
const tableData = ref<any[]>([])
const projectTitle = ref<string>('')
const tableColumnDate = ref<any[]>([])
const tableWrap = ref<HTMLElement | null>(null)
const tableHeight = ref(500)
const deptProps = ref({ multiple: true, label: 'deptName', value: 'deptId' })
const projectTypes = ref<IProjectTypes[]>(useTaskTypeStore().getAllState())
const projectList = ref<Array<{ id: number; code: string; cname: string }>>(projectssStore.getAllState() as any)
const queryForm = reactive({
  user: '',
  projectId: '',
  date: [] as Date[],
  deptIds: [] as string[] | number[],
  timelogCategory: '',
})

/**
 * 将数据绑定到表格中
 *
 * @param data 要绑定到表格的数据
 * @returns 无返回值
 */
const bindDataToTable = async (data: any) => {
  tableData.value = data
  nextTick(() => {
    const tableWrapElement = tableWrap.value
    if (tableWrapElement) {
      // 设置表格高度
      tableHeight.value = tableWrapElement.offsetHeight
      // 延迟执行，等待表格渲染完成后再设置
      setTimeout(() => {
        if (tableWrapElement) {
          // 表格的最后一行前两个单元格合并
          const tds = tableWrapElement.querySelectorAll('.el-table__footer td')
          const tbs0 = tds[0] as HTMLElement
          tbs0.setAttribute('colspan', '2')
          tbs0.style.textAlign = 'center'
          tds[1].remove()
        }
      }, 200)
    }
  })
}

/**
 * 计算表格数据中的汇总信息
 *
 * @param param 包含表格列信息和数据的对象
 * @returns 返回汇总信息的数组，每个元素可能是字符串或VNode，表示该列的汇总结果
 */
const getSummaries = (param: any) => {
  const { columns, data } = param
  const sums: any[] = []
  columns.forEach((column: any, index: number) => {
    if (index === 0) {
      sums[index] = h('div', {}, ['Total Headcount'])
      return
    }
    const values = data.map((item: any) => Number(item[column.property]))
    // sums[index] = '0'
    if (!values.every((value: any) => Number.isNaN(value))) {
      sums[index] = values.reduce((prev: any, curr: any) => {
        const value = Number(curr)
        if (!Number.isNaN(value)) {
          return prev + curr
        } else {
          return prev
        }
      }, 0)
    } else {
      // console.log(index)
      sums[index] = ''
    }
  })
  sums[1] = ''
  return sums
}

/**
 * 异步获取数据
 *
 * @param startTimelogDate 开始时间
 * @param endTimelogDate 结束时间
 * @returns 返回数据行
 */
const fetchData = async (startTimelogDate: any, endTimelogDate: any) => {
  projectTitle.value = `${startTimelogDate} - ${endTimelogDate} 项目统计`
  const params = {
    startTimelogDate,
    endTimelogDate,
  }
  const deptIds: any[] = []
  queryForm.deptIds.forEach((e: any) => {
    deptIds.push(e[e.length - 1])
  })
  if (queryForm.user !== '') {
    Object.assign(params, { userName: queryForm.user })
  }
  if (deptIds.length > 0) {
    Object.assign(params, { deptIds: deptIds.join(',') })
  }
  if (queryForm.timelogCategory !== '') {
    Object.assign(params, { timelogCategory: queryForm.timelogCategory })
  }
  if (queryForm.timelogCategory === '0' && queryForm.projectId !== '') {
    Object.assign(params, { projectId: queryForm.projectId })
    const projectItem = projectList.value.find((e: any) => e.id == queryForm.projectId)
    if (projectItem) {
      projectTitle.value = `${projectItem.code}-${projectItem.cname} ` + projectTitle.value
    }
  }
  if (queryForm.timelogCategory === '0' && queryForm.projectId === '') {
    ElMessage.error('必须选择项目')
    return
  }
  const res = await http({
    method: 'GET',
    path: '/dev-api/oa/hrm/list',
    params,
  })
  const { rows } = res
  return rows
}
const getDataList = async () => {
  if (queryForm.date.length == 2) {
    const [start, end] = queryForm.date
    // console.log(projectList.value)
    // const showTypeItem = tableTypeList.value[showType.value]

    const weeks = utils.getWeeksBetweenDates(start, end)
    // const [first] = weeks
    // const [last] = weeks.slice(-1)
    const startTimelogDate = utils.formatDate(start, 'yyyy-MM-dd')
    const endTimelogDate = utils.formatDate(end, 'yyyy-MM-dd')

    // 设置 table 列
    tableColumnDate.value = [
      ...weeks.map((e) => {
        const start = utils.formatDate(e.start, 'yyyy-MM-dd')
        const end = utils.formatDate(e.end, 'yyyy-MM-dd')
        const startYear = utils.formatDate(e.start, 'yyyy')
        const endYear = utils.formatDate(e.end, 'yyyy')
        const startDay = utils.formatDate(e.start, 'MM-dd')
        const endDay = utils.formatDate(e.end, 'MM-dd')
        return { label: start, columnName: `${start} - ${end}`, start, end, startDay, endDay, startYear, endYear }
      }),
    ]
    // minutes 每天工作时长 （长春 400 分钟）
    // 一周 5 天
    // const weekMinutes = minutes * 5 // 一周 工作 5 天 时长

    const rows = await fetchData(startTimelogDate, endTimelogDate)
    const result: any = {}
    rows.forEach((row: any) => {
      // row.push
      // deptId,deptName,parentDeptName,userSum
      const key = `${row.deptId}-${row.deptName}`
      if (!result[key]) {
        result[key] = {
          ...row,
        }
      }
      // const dateRange = `${row.weekStartDate} - ${row.weekEndDate}`
      // result[key][dateRange] = row.durationTime
      // result[key][row.weekStartDate] = row.durationTime
    })
    for (const key in result) {
      const e = result[key]
      for (let index = 0; index < tableColumnDate.value.length; index++) {
        const temp = tableColumnDate.value[index]
        if (!e[temp.columnName]) {
          e[temp.columnName] = e.userSum
        }
        // const colVal = (e[temp.columnName] * 1000) / workingHours.value / currentShowTypeItem.value.days
        e[temp.start] = e.userSum
        e[temp.columnName] = e.userSum
        e[temp.columnName + ':val'] = e.userSum
      }
    }
    // console.log('result', result)
    await bindDataToTable(Object.values(result))
  }
}

/**
 * 重置表单
 *
 * 重置查询表单的所有字段到初始状态，包括用户、项目ID、日期范围、部门ID数组和时间日志类别
 */
const resetForm = () => {
  isQueryed.value = false
  tableData.value = []
  projectTitle.value = ''
  const [start, end] = utils.getDateRangeByDate(utils.shortcutsType.前后半年) as Date[]
  queryForm.user = ''
  queryForm.projectId = ''
  queryForm.date = [start, end]
  queryForm.deptIds = [] as string[] | number[]
  queryForm.timelogCategory = ''
  handleClickBtnSubmit()
}
/**
 * 提交表单处理函数
 *
 * @returns {Promise<void>} 返回一个异步操作的Promise对象，无返回值
 */
const handleClickBtnSubmit = async () => {
  // console.log('queryForm', queryForm)
  isQueryed.value = true
  tableData.value = []
  projectTitle.value = ''
  if (queryForm.date.length == 2) {
    await getDataList()
  }
}
/**
 * 重置按钮点击事件处理函数
 *
 * @returns 无返回值
 */
const handleClickBtnReset = async () => {
  await resetForm()
}

onMounted(async () => {
  await handleClickBtnReset()
})
</script>
<style lang="scss" scoped>
.resource-management {
  display: flex;
  flex-direction: column;
  .form-container {
    display: flex;
    justify-content: flex-start;
  }
  .table-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    .table-wrap {
      flex: 1;
    }
  }
}
.table-header-cell {
  writing-mode: vertical-lr;
  // line-height: 1;
}
</style>
